package com.everflourish.yeah100.act.welcome;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.RelativeLayout;

import com.android.volley.Response;
import com.android.volley.Response.ErrorListener;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.everflourish.yeah100.R;
import com.everflourish.yeah100.act.base.BaseActivity;
import com.everflourish.yeah100.act.menu.HomeActivity;
import com.everflourish.yeah100.entity.userinfo.LoginInfo;
import com.everflourish.yeah100.http.HttpURL;
import com.everflourish.yeah100.http.LoginAndRegisterRequest;
import com.everflourish.yeah100.utils.IntentUtil;
import com.everflourish.yeah100.utils.MyToast;
import com.everflourish.yeah100.utils.SPUtil;
import com.everflourish.yeah100.utils.StringUtil;
import com.everflourish.yeah100.utils.Yeah100;
import com.everflourish.yeah100.utils.constant.Constant;
import com.everflourish.yeah100.utils.constant.ResultCode;
import com.everflourish.yeah100.utils.constant.RoleEnum;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * 欢迎页面
 * 作者：Created by Administrator on 2016/6/2.
 * 时间：2016/6/2
 */
public class StartActivity extends BaseActivity {

    protected static final String TAG = null;
    private LoginAndRegisterRequest mRequest;
    private RelativeLayout mStartRl;
    private SPUtil spUtil;
    private String mUserName;
    private String mPassword;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_start);
        initData();
        initView();
    }

    private void initData() {
        spUtil = SPUtil.getSharedPreferences(mContext, SPUtil.FILE_NAME);
    }

    private void initView() {
        mStartRl = (RelativeLayout) this.findViewById(R.id.start_rl);
        showAlphaAnimation();
    }

    private void showAlphaAnimation() {
        AlphaAnimation anim = new AlphaAnimation(0f, 1f);
        anim.setDuration(1000);
        anim.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
                mQueue = Volley.newRequestQueue(mContext);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {
            }

            @Override
            public void onAnimationEnd(Animation animation) {
                autoLogin();
            }
        });
        anim.setFillAfter(true);
        mStartRl.setAnimation(anim);
        anim.startNow();
    }

    private void autoLogin() {
        mRequest = LoginAndRegisterRequest.getInstance();
        boolean isFirstUse = spUtil.getBoolean(SPUtil.IS_FIRST_USE,
                true);
        if (isFirstUse) {
            IntentUtil.startActivity(StartActivity.this,
                    WelcomeActivity.class, true);
            return;
        }
        mUserName = spUtil.getString(SPUtil.USER_NAME, null);
        mPassword = spUtil.getString(SPUtil.PASSWORD, null);
        if (!TextUtils.isEmpty(mUserName)
                && !TextUtils.isEmpty(mPassword)) {// 判断是否已经保存帐号密码，如果是，自动登录
            userLogin(mUserName, mPassword);
        } else {
            IntentUtil.startActivity(StartActivity.this, LoginActivity.class, true);
        }
    }

    private void userLogin(String userName, String password) {
        JsonObjectRequest userLoginRequest = mRequest.userLogin(userName,
                password, new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        loginListener(response);
                    }
                }, new ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        gotoLogin(mUserName, mPassword, "自动登录失败");
                    }
                });
        mQueue.add(userLoginRequest);
    }

    /**
     * @param response
     */
    private void loginListener(JSONObject response) {
        Gson gson = new Gson();
        Yeah100.loginInfo = gson.fromJson(response.toString(),
                LoginInfo.class);
        if (Yeah100.loginInfo == null
                || Yeah100.loginInfo.resultCode == null) {
            MyToast.showLong(mContext, "登录失败");
            return;
        }
        if (Yeah100.loginInfo.resultCode
                .equals(ResultCode.result_ok.resultCode)) {
            Yeah100.userId = Yeah100.loginInfo.userInfo.id;
            if (Yeah100.loginInfo.userInfo.photoId != null) {
                Yeah100.userImageUrl = new HttpURL().URL_IMAGE_GET
                        + Yeah100.loginInfo.userInfo.photoId.replace(".jpg", "");
            } else {
                Yeah100.userImageUrl = "";
            }
            if (Yeah100.isActivated()) {
                // 设置-是否是老师身份
                if (!StringUtil.stringIsNull(Yeah100.loginInfo.userInfo.lastRole)
                        && Yeah100.loginInfo.userInfo.lastRole.equals(RoleEnum.TEACHER.name)) {
                    Yeah100.mRoleEnum = RoleEnum.TEACHER;
                    IntentUtil.startActivity(StartActivity.this, HomeActivity.class, true);
                } else {
//                    Yeah100.mRoleEnum = RoleEnum.STUDENT;
                    showConvertRoleDialog();
                }
            } else {
                Yeah100.mRoleEnum = RoleEnum.STUDENT;
                AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
                builder.setMessage("暂不支持学生身份登录，关注易100微信公众号，即可轻松查询考试成绩！");
                builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        IntentUtil.startActivity(StartActivity.this, LoginActivity.class, true);
                    }
                });
                builder.show();
            }
        } else {
            gotoLogin(mUserName, mPassword, "自动登录失败");
        }
    }

    private void gotoLogin(String userName, String password, String errorMsg) {
        Intent intent = new Intent(mContext, LoginActivity.class);
        intent.putExtra("userName", userName);
        intent.putExtra("password", password);
        intent.putExtra("errorMsg", errorMsg);
        StartActivity.this.startActivity(intent);
        finish();
    }

    private void showConvertRoleDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setCancelable(false);
        builder.setMessage("暂不支持学生身份登录，是否切换为教师身份登录？");
        builder.setPositiveButton("切换并登录", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                roleUpdateRequest(RoleEnum.TEACHER);
            }
        });
        builder.setNegativeButton("否", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                gotoLogin(mUserName, mPassword, "自动登录失败");
                dialog.dismiss();
            }
        });
        builder.show();
    }

    /**
     * 切换老师身份登录请求
     *
     * @param roleEnum
     */
    private void roleUpdateRequest(RoleEnum roleEnum) {
        JsonObjectRequest request = mRequest.roleUpdateRequest(roleEnum,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        roleUpdateListener(response);
                    }
                }, new ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        mRequest.disposeError(mContext, null, error, "自动登录失败");
                    }
                });
        mQueue.add(request);
    }

    /**
     * 切换为老师身份登录监听
     *
     * @param response
     */
    private void roleUpdateListener(JSONObject response) {
        String resultCode = "";
        try {
            resultCode = response.getString(Constant.RESULT_CODE);
            if (resultCode
                    .equals(ResultCode.result_ok.resultCode)) {
                Yeah100.mRoleEnum = RoleEnum.TEACHER;
                IntentUtil.startActivity(StartActivity.this, HomeActivity.class, true);
            } else {
                MyToast.showLong(mContext, "自动登录失败");
            }
        } catch (JSONException e1) {
            e1.printStackTrace();
        } finally {
            if (!resultCode.equals(ResultCode.result_ok.resultCode)) {
                IntentUtil.startActivity(StartActivity.this, LoginActivity.class, true);
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mQueue.stop();
    }
}
